package _1连接数据库;

//瀵煎叆java.sql涓嬮潰鐨勫寘

//杩炴帴
import java.sql.Connection;
//椹卞姩
import java.sql.DriverManager;
import java.sql.ResultSet;
//寮傚父
import java.sql.SQLException;
//鏌ヨ
import java.sql.Statement;



public class TestDemo {

	public static void main(String[] args) 
	{
		
		// 1. 鍔犺浇椹卞姩
		// 娉ㄥ唽MySQL椹卞姩
//		DriverManager.registerDriver(new com.mysql.jdbc.Driver());
		
		// 閫氳繃鏌ョ湅婧愮爜,鍔犺浇绫诲悗鑷姩娉ㄥ唽
//	    // Register ourselves with the DriverManager
//	    static {
//	        try {
//	            java.sql.DriverManager.registerDriver(new Driver());
//	        } catch (SQLException E) {
//	            throw new RuntimeException("Can't register driver!");
//	        }
//	    }
		
		// 鏀规垚鍔犺浇绫�
		// =>
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			System.out.println("娌℃湁鎵惧埌椹卞姩,妫�鏌ユ槸鍚︽湁娣诲姞mysql椹卞姩jar鍖�");
			return;
		}
		
		
		// 2. 杩炴帴鏁版嵁搴�
		// 鏈嶅姟鍣ㄥ湴鍧�
		// 绔彛
		// 鐢ㄦ埛鍚�
		// 瀵嗙爜
		String url = "jdbc:mysql://localhost:3306/mydb";
		String username = "root";
		String password = "123456";		
		Connection conn=null;
		try {
			conn = DriverManager.getConnection(url, username,password);
		} catch (SQLException e) {
			System.out.println("杩炴帴鏁版嵁搴撳紓甯�:"+e.getMessage());
			return;
		}
		
		
		// 3. 鏌ヨ
		Statement stmt=null;
		try {
			stmt = conn.createStatement();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// 鏇存柊璇彞
//		String sql = "insert into category value (4,'鐜╁叿')";
//		String sql = "delete from category where cid=4";
//		String sql = "update category set cname='濂宠' where cid=30";
//		int result=stmt.executeUpdate(sql);
//		System.out.println("褰卞搷琛屾暟"+result);
		
		// 鏌ヨ璇彞
		String sql = "select * from category";
		ResultSet rs=null;
		try {
			rs = stmt.executeQuery(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			while(rs.next()) // 鎸囧悜涓嬩竴琛岀粨鏋�
			{
				// 寰楀埌绗嚑鍒楁暟鎹�
				int cid = rs.getInt(1);  // 浠�1寮�濮�
				String cname = rs.getString(2);
				// 鏍规嵁瀛楁鍚嶈幏鍙�
//			int cid = rs.getInt("cid");
//			String cname = rs.getString("cname");
				System.out.println(cid+"--"+cname);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		// 4. 閲婃斁璧勬簮
		if(rs!=null)
		{
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(stmt!=null)
		{
			try {
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		
//		try {
//			rs.close();
//			stmt.close();
//			conn.close();
//			
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}

		
	
	}

}
